package bg.cinema_system.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import bg.cinema_system.global.ConnectionJDBC;

public class SeatDAO {
	
	public static boolean reserveSeat(int seat_number, int fk_hall_id, int fk_reservation_id) throws SQLException  {
		
		Connection dbConnection = ConnectionJDBC.getConnection();

		if (dbConnection == null) {
			throw new SQLException("Class SeatsDAO: Can't get database connection");
		}

		String sqlStatement = "INSERT INTO cinema.seats " 
		+ " (seat_number, fk_hall_id, fk_reservation_id) "
		+ " VALUES (?, ?, ?)";

		PreparedStatement ps = null;
		int result = 0;
		try {
			ps = dbConnection.prepareStatement(sqlStatement);
			ps.setInt(1, seat_number);
			ps.setInt(2, fk_hall_id);
			ps.setInt(3, fk_reservation_id);
			
			result = ps.executeUpdate();
		} catch (SQLException e) {
			throw new SQLException(e);
		} finally {
			try {
				// Close all connections
				ps.close();
				dbConnection.close();
			} catch (SQLException e) {
				throw new SQLException(e);
			}
		}

		if (result != 0) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean buySeat(int fk_ticket_id, int fk_reservation_id) throws SQLException {
		
		Connection dbConnection = ConnectionJDBC.getConnection();

		if (dbConnection == null) {
			throw new SQLException("Class SeatsDAO: Can't get database connection");
		}

		String sqlStatement = "UPDATE cinema.seats " 
		+ " SET seats.fk_ticket_id = ? "
		+ " WHERE seats.fk_reservation_id = ? ";

		PreparedStatement ps = null;
		int result = 0;
		try {
			ps = dbConnection.prepareStatement(sqlStatement);
			ps.setInt(1, fk_ticket_id);
			ps.setInt(2, fk_reservation_id);
			
			result = ps.executeUpdate();
		} catch (SQLException e) {
			throw new SQLException(e);
		} finally {
			try {
				// Close all connections
				ps.close();
				dbConnection.close();
			} catch (SQLException e) {
				throw new SQLException(e);
			}
		}

		if (result != 0) {
			return true;
		} else {
			return false;
		}
	}
}
